// AuthServiceImpl.java
package swb.api.com.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import swb.api.com.repository.dto.SysUser;
import swb.api.com.service.AuthService;
import swb.api.com.service.SysUserService;
import swb.api.com.service.SysRoleService;
import swb.api.com.utils.JwtUtil;
import swb.api.com.vo.req.LoginRequest;
import swb.api.com.vo.resp.LoginResponse;

import java.util.List;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public LoginResponse login(LoginRequest loginRequest) {
        // 查找用户
        SysUser user = sysUserService.findByUsername(loginRequest.getUsername());
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 验证密码
        if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        // 生成token
        String token = jwtUtil.generateToken(user.getUsername());

        // 获取用户权限
        List<String> permissions = sysRoleService.getPermissionsByUserId(user.getId());

        // 构造响应
        LoginResponse response = new LoginResponse();
        response.setToken(token);
        response.setUser(user);
        response.setPermissions(permissions);

        return response;
    }
}
